'use strict';

const moment = require('moment');
const async = require('async');

const Controller = require('../../core/common');

class GoodsController extends Controller {

  async index() {
    const { ctx, app } = this;

    // title 在关联字段里面查询
    const { nickname, sponsor, endAt, style, type, status } = ctx.request.query;

    const attributes = {};
    const where = {};
    sponsor && Object.assign(where, { sponsor });
    style && Object.assign(where, { style });
    type && Object.assign(where, { type });
    status && Object.assign(where, { status });
    nickname && Object.assign(where, { nickname: { '$like': `%${nickname}%` } });

    const data = await ctx.service.v1.goods.findAll({ where });
    await new Promise((resolve, reject) => {
      async.each(data.rows, async (item, callback) => {
        const pv = await app.redis.get('goods').get(`goodsUsers_pv_${item.id}`) || 0;
        const uv = await app.redis.get('goods').scard(`goodsUsers_uv_${item.id}`) || 0;
        item.setDataValue('pv', Number(pv));
        item.setDataValue('uv', Number(uv));
        callback(null);
      }, err => err ? reject(err) : resolve());
    });

    this.success(data);
  }

  async show() {
    const { ctx, app } = this;

    const { id } = ctx.params;

    // 记录 pv uv
    await app.redis.get('goods').sadd(`goodsUsers_uv_${id}`, String(ctx.ip));
    await app.redis.get('goods').incr(`goodsUsers_pv_${id}`);

    // 获取抽奖
    // const goodsRes = await ctx.model.Goods.findOne({ where: { id } });
    // if (!goodsRes) return this.success(null, '商品不存在', -1);
    const data = await ctx.service.v1.goods.findById(id);

    this.success(data);
  }

  async create() {
    const { ctx, app } = this;

    const { style } = ctx.request.body;

    if (style === '0') {
      const { endAt } = ctx.request.body;
      const currenttime = moment().unix();
      const endtime = moment(endAt).unix();
      if (endtime > currenttime) {
        const data = await ctx.service.v1.goods.create(ctx.request.body);
        const { id } = data || {};
        // 消息过期提醒
        await app.redis.get('expired').set(`goods_endAt_${id}`, JSON.stringify(data));
        await app.redis.get('expired').expire(`goods_endAt_${id}`, endtime - currenttime);
        return this.success(data);
      }
      return this.success(null, '开奖时间应该大于当前时间', -1);
    }
    if (style === '1') {
      const { number } = ctx.request.body;
      if (number >= 0) {
        const data = await ctx.service.v1.goods.create(ctx.request.body);
        const { id } = data || {};
        // 记录奖品人数
        await app.redis.get('goods').set(`goodsUsers_maxNum_${id}`, number);
        return this.success(data);
      }
      return this.success(null, '开奖人数应该大于1', -1);
    }
    return this.success(null, '不知道你在做什么', -1);
  }

  async update() {
    const { ctx } = this;

    const { id = '' } = ctx.params;

    const { isEdit, type, GoodsPrizes, GoodsFigures, Banner } = ctx.request.body;

    let data = null;
    if (isEdit) {
      // 从进行中的编辑过来的修改
      Array.isArray(GoodsPrizes) && GoodsPrizes.forEach(async item => {
        await ctx.model.GoodsPrizes.update(item, { where: { goodsId: id, id: item.id } })
      });
      Array.isArray(GoodsFigures) && GoodsFigures.forEach(async item => {
        await ctx.model.GoodsFigures.update(item, { where: { goodsId: id, id: item.id || id } })
      });
      data = await ctx.service.v1.goods.update(ctx.request.body, {
        where: { id },
      });
    } else if (Number(type)) {
      // 从首页过来的上首页配置
      data = await ctx.service.v1.goods.update(ctx.request.body, {
        where: { id },
      }).then(results => {
        // 更新广告的 goodsId
        if (Banner) return ctx.model.Banners
          .update({ goodsId: 0 }, { where: { goodsId: id } })
          .then(() => ctx.model.Banners.update(Banner, { where: { id: Banner.id } }));
        return results;
      });
    } else {
      data = await ctx.service.v1.goods.update(ctx.request.body, {
        where: { id: id.indexOf(',') === -1 ? id : { '$in': id.split(',') } }
      });
    }
    this.success(data);
  }

  async destroy() {
    const { ctx } = this;

    const { id = '' } = ctx.params;

    const data = await ctx.service.v1.goods.destroy({ where: { id: id.indexOf(',') === -1 ? id : { '$in': id.split(',') } } });

    this.success(data);
  }

}

module.exports = GoodsController;